package schach.client.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import rmi.tests.Inter;
import schach.GameController;
import schach.client.view.SchachbrettClient;
import schach.server.controller.GameControllerImpl;

public class ClientController {

	private Registry reg;
	private GameController controller;
	private SchachbrettClient brett;
	private InputStream input;
	Socket server;
	public ClientController(SchachbrettClient schachbrett) throws IOException, NotBoundException{
		this.brett = schachbrett;
		reg = LocateRegistry.getRegistry("127.0.1.1",
				1099);

		controller= (GameController) reg.lookup("GameController");
		controller.toString();
		
		
		server = new Socket("localhost", 1234);
		/*
		InputStream input = server.getInputStream();
		OutputStream output = server.getOutputStream();
		output.write(5);
		output.write(10);
		output.flush();
		System.out.println(input.read());
		server.close();
		input.close();
		output.close();
		*/
	}

	public GameController getController() {
		return controller;
	}
	public void empfange(){
		Thread empfange = new Thread(new EmpfangeZug());
		empfange.start();
	}
	private class EmpfangeZug implements Runnable{

		@Override
		public void run() {
			System.out.println("Empfange Client");
			try {
				input = server.getInputStream();
				if(input.read() == 10){
					brett.setAmZug(true);
					brett.paint(brett.getGraphics());
					System.out.println("Empfangen client");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	public void sendeZug(){
		Thread senden = new Thread(new ZugSendung());
		senden.start();
	}
	private class ZugSendung implements Runnable{
		
		public void run(){
			try {
				OutputStream output = server.getOutputStream();
				output.write(10);
				output.flush();
				brett.setAmZug(false);
				System.out.println("Gesendet Client");
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


}
